/*Hm9gUKDDwtNjV7Mk8onAzgXlk2sN3YqGeiNBfMPmEAaQ5tb/cjXQzjs3lVWuDzNj*/
//按钮点击事件处理
import { ajax, toast, print, output, cardCache, DongbaToLocalTime, getLangCode, formDownload } from 'nc-lightapp-front';
import constant from '../../constants';
import { pageConfig } from '../const';
import { changeItem } from './index';
import ampub from 'ampub';
import moment from 'moment';
import { click2Event } from './afterEvent';
const { components, commonConst, utils } = ampub;
const { CommonKeys, StatusUtils, SagaConst } = commonConst;
const { multiLangUtils, msgUtils, cardUtils } = utils;
const { getMultiLangByID } = multiLangUtils;
const { showConfirm, showMessage, MsgConst } = msgUtils;
const { setHeadAreaData } = cardUtils;
const { approveConst } = CommonKeys;
const { VOSTATUS } = StatusUtils;
const { SagaStatus } = SagaConst;

const { LoginContext } = components;
const { getContext, loginContextKeys } = LoginContext;

const {
	printFilename,
	formId,
	area,
	pagecode,
	pkField,
	bill_type,
	transi_type,
	url,
	listRouter,
	dataSource
} = pageConfig;
export default function buttonClick(props, id) {
	//按钮事件处理
	switch (id) {
		// 删除
		case 'Delete':
			delConfirm.call(this, props);
			break;
		// 编辑
		case 'Edit':
			editAction.call(this, props);
			break;
		// 提交
		case 'Commit':
			commit.call(this, 'SAVE', props);
			break;
		// 收回
		case 'UnCommit':
			commit.call(this, 'UNSAVE', props);
			break;
		// 刷新
		case 'Refresh':
			refresh.call(this, props);
			break;
		// 打印
		case 'Print':
			printTemp.call(this, props);
			break;
		// 输出
		case 'Output':
			outputTemp.call(this, props);
			break;
		// 下一步
		case 'Next':
			next.call(this, props);
			break;
		// 确认
		case 'Confirm':
			stepDone.call(this, props);
			break;
		// 上一步
		case 'Previous':
			prev.call(this, props);
			break;
		// 保存
		case 'Save':
			save.call(this, props);
			break;
		// 重新分配盘点人
		case 'ReInventoryPeople':
			allotAgain.call(this, props);
			break;
		// 重新分配
		case 'ReInventory':
			reInventory.call(this, props);
			break;
		// 取消
		case 'Cancel':
			cancel.call(this, props);
			break;
		// 增行
		case 'AddLine':
			addLine.call(this, props);
			break;
		// 附件
		case 'Attachment':
			attachment.call(this, props);
			break;
		// 批改
		case 'BatchAlter':
			batchAlterAction.call(this);
			break;
		// 全部相符
		case 'AllMatch':
			allMatch.call(this, props);
			break;
		// 导入
		case 'ImportBtn':
			Import.call(this, props);
			break;
		// 导出
		case 'ExportBtn':
			Export.call(this, props);
			break;
		// 审批详情
		case 'QueryAboutBillFlow':
			this.setState({
				showApprove: true,
				transi_type: this.childformData.head.transi_type.value
					? this.childformData.head.transi_type.value
					: this.childformData.head.transi_type
			});
			break;
		default:
			break;
	}
}

// 转换东八区为当地时间
export function changeTime(time, format = 'YYYY-MM-DD') {
	if (time) {
		let newTime = DongbaToLocalTime(moment(time));
		return newTime.format(format);
	}
}
// let BeijinVal = time && moment(time).toDate();
// let beijingZoneHours = time && moment(time).toDate().getHours();
// let offsetZone = new Date().getTimezoneOffset() / 60;
// offsetZone += 8;
// BeijinVal && BeijinVal.setHours(beijingZoneHours - offsetZone);
//return time && moment(BeijinVal).format('YYYY-MM-DD');

/**
* 删除
* @param {*} props 
*/
export function delConfirm(props) {
	let pk = this.state.pk_inventory;
	if (!pk) {
		return;
	}
	showConfirm.call(this, props, {
		type: MsgConst.Type.Delete,
		beSureBtnClick: singleDel
	});
}
/**
 * 删除
 * @param {*} props 
 * @param {*} operatorType 
 * @param {*} commitType 
 */
function singleDel(props) {
	let id = this.state.pk_inventory;
	let ts = '';
	if (this.state.current == 7) {
		ts = this.ts;
	} else {
		ts = this.childformData.head[0].values.ts.value;
	}
	let paramInfoMap = {};
	paramInfoMap[id] = ts;
	ajax({
		url: url.commit,
		data: {
			paramInfoMap: paramInfoMap,
			dataType: 'listData',
			OperatorType: 'DELETE',
			pageid: pagecode,
			commitType: 'commit' //提交
		},
		success: (res) => {
			linkToList.call(this, props, undefined, 'browse');
		},
		error: (res) => {
			if (res && res.message) {
				toast({ content: res.message, color: 'danger' });
			}
		}
	});
}
//提交 TODO
export function commit(OperatorType, props, content) {
	let paramInfoMap = {};
	let ts = this.ts;
	paramInfoMap[this.state.pk_inventory] = ts;
	let that = this;
	ajax({
		url: url.commit,
		data: {
			paramInfoMap: paramInfoMap,
			dataType: 'listData',
			OperatorType: OperatorType,
			pageid: pagecode,
			commitType: 'commit',
			content: content
		},
		success: (res) => {
			if (content) {
				this.setState({
					compositedisplay: false
				});
			}
			if (res.data.success === approveConst.HASAPPROVEALTRAN) {
				//指派信息
				let workflowData = res.data.approvealTranData;
				if (
					workflowData.workflow &&
					(workflowData.workflow == approveConst.APPROVEFLOW ||
						workflowData.workflow == approveConst.WORKFLOW)
				) {
					this.setState({
						compositedata: workflowData,
						compositedisplay: true
					});
				}
			} else {
				if (res.data.success === approveConst.ALLSUCCESS) {
					this.childformData.head = JSON.parse(
						JSON.stringify(res.data.cardVos[0].head.card_head.rows[0].values)
					);
					// 处理盘点范围多语
					handleCheck_range.call(this, res.data.cardVos[0].head.card_head.rows[0].values.check_range, true);
					this.childformData.head.check_range =
						res.data.cardVos[0].head.card_head.rows[0].values.check_range.value;
					let bill_status =
						res.data.cardVos[0].head[constant.AREA.CARD.BODY_HEAD].rows[0].values.bill_status.value;
					this.ts = res.data.cardVos[0].head[constant.AREA.CARD.BODY_HEAD].rows[0].values.ts.value;
					that.setState({ bill_status }, () => {
						toggleShow(that, props);
					});
					cardCache.updateCache(
						'pk_inventory',
						res.data.cardVos[0].head[constant.AREA.CARD.BODY_HEAD].rows[0].values['pk_inventory'].value,
						res.data.cardVos[0],
						constant.AREA.CARD.BODY_HEAD,
						constant.DATASOURCE
					);
					toast({ content: res.data.successMsg, color: 'success' });
				} else {
					toast({ content: res.data.errorMsg, color: 'warning' });
				}
			}
		},
		error: (res) => {
			if (res && res.message) {
				toast({ content: res.message, color: 'danger' });
			}
		}
	});
}
/**
* 刷新
* @param {*} props 
*/
export function refresh(props) {
	let pk = this.state.pk_inventory;
	loadingResultData.call(this, pk, () => {
		showMessage.call(this, props, { type: MsgConst.Type.RefreshSuccess });
	});
}
/**
 * 打印
 * @param {*} props 
 */
export function printTemp(props) {
	let current = this.state.current;
	let printData = getPrintData.call(this, props, 'print');
	if (!printData) {
		showMessage.call(this, props, { type: MsgConst.Type.ChoosePrint });
		return;
	}
	if (current == 7) {
		//打印时将html标题改为单据名称
		let title = document.getElementsByTagName('title');
		if (title && title[0]) {
			title[0].innerHTML = getMultiLangByID('201203004A-000059');
		}
		window.print(
			'pdf' // 支持两类：'html'为模板打印，'pdf'为pdf打印
		);
	} else {
		print(
			'pdf', // 支持两类：'html'为模板打印，'pdf'为pdf打印
			constant.URL.PRINT_CARD, // 后台打印服务url
			printData
		);
	}
}

/**
 * 输出
 * @param {*} props 
 */
export function outputTemp(props) {
	let current = this.state.current;
	let printData = getPrintData.call(this, props, 'output');
	if (!printData) {
		showMessage.call(this, props, { type: MsgConst.Type.ChooseOutput });
		return;
	}
	//如果是查询结果页面，需要将全部数据输出
	if (current == 7) {
		printData.oids[1] = '5';
	}
	output({
		url: url.print_card,
		data: printData
	});
}
/**
* 获取打印数据
* @param {*} props 
* @param {*} outputType 
*/
function getPrintData(props, outputType = 'print') {
	let pk = this.state.pk_inventory;
	let checkResult = this.checkResult;
	if (!pk) {
		return false;
	}
	let filenameValue = getMultiLangByID(printFilename);
	let pks = [ pk, checkResult ];
	let printData = {
		filename: filenameValue, // 文件名称
		nodekey: null, // 模板节点标识
		oids: pks, // 需要打印数据主键
		outputType // 输出类型
	};
	return printData;
}
/* 确定按钮 */
export function stepDone(props) {
	this.state.isLeaveOrRefresh = true;
	//第二步未分配确定按钮
	if (this.state.inventoryStatus === 'unAllot') {
		// 分配盘点人中的数据
		let assignTable = [];
		if (this.state.inventoryWay != 1) {
			if (this.tempEditTableDatas.rows && this.tempEditTableDatas.rows.length > 0) {
				assignTable = this.tempEditTableDatas.rows;
			}
		}
		// 获取传输的数据
		let queryInfo = getQueryInfo(props);
		let unAllotData = getUnAllotInfo(props);
		let assignData = getAssignInfo(props);
		let tempUserdefObj = {
			// JSON.stringify(assignData);
			inventoryWay: this.state.inventoryWay,
			signature: this.signature,
			start_date: this.echartsData.start_date,
			end_date: this.echartsData.end_date
		};
		queryInfo.userdefObj = tempUserdefObj;
		let cardData = this.props.cardTable.getAllData(constant.AREA.STEP.ANEWALLOT);
		unAllotData.model.rows = cardData.rows;
		assignData.model.rows = assignTable;
		queryInfo.userdefObj.assignData = JSON.stringify(assignData);
		queryInfo.userdefObj.unAllotData = JSON.stringify(unAllotData);
		ajax({
			url: url.query_assign,
			data: queryInfo,
			success: (res) => {
				if (res.success) {
					// 防止重复显示，先制空
					this.echartsData.linedata.data = [];
					this.echartsData.linedata.name = [];
					// 设置资产的数量
					this.echartsData.total_num = res.data.body[area.card.body_area].rows.length;
					// 设置盘点范围
					this.echartsData.check_range = handleCheck_range.call(
						this,
						res.data.head[area.card.body_head].rows[0].values.check_range.value,
						true
					);
					this.childformData.head = res.data.head[area.card.body_head].rows;
					this.childformData.body = res.data.body[area.card.body_area].rows;
					let tempRows = [];
					res.data.body[area.card.body_area].rows.map((row) => {
						//存储没有分配盘点人的数据
						if (row.values && row.values.inventory_checkuser && !row.values.inventory_checkuser.value) {
							tempRows.push(row);
						}
					});
					if (tempRows.length > 0) {
						cardData.rows = tempRows;
						this.tempCardTableDatas = cardData;
					}

					/* 给图标界面赋值 */
					setEcharsData.call(this, res);
					let current = this.state.current + 1;
					this.setState({ current });
					toggleShow(this, props);
				}
			},
			error: (res) => {
				if (res && res.message) {
					toast({ content: res.message, color: 'danger' });
				}
			}
		});
		// 确认后未分配盘点人
	} else if (this.state.current != 7 && this.state.inventoryStatus === 'confirmedAllot') {
		// 分配盘点人中的数据
		let assignTable = [];
		if (this.state.inventoryWay != 1) {
			if (this.tempEditTableDatas.rows && this.tempEditTableDatas.rows.length > 0) {
				assignTable = this.tempEditTableDatas.rows;
			}
			// 使用人盘点
		} else {
			assignTable = [
				{
					values: {
						inventoryway: {
							display: null,
							scale: null,
							value: '1'
						}
					}
				}
			];
		}
		// 获取传输的数据
		let queryInfo = {};
		let unAllotData = getUnAllotInfo(props);
		let assignData = getAssignInfo(props);

		let tempUserdefObj = {
			// JSON.stringify(assignData);
			inventoryWay: '' + this.state.inventoryWay,
			signature: this.signature,
			pk_inventory: this.state.pk_inventory
		};
		queryInfo.userdefObj = tempUserdefObj;
		unAllotData.model.rows = this.props.cardTable.getAllRows(constant.AREA.STEP.ANEWALLOT);
		assignData.model.rows = assignTable;
		queryInfo.userdefObj.assignData = JSON.stringify(assignData);
		queryInfo.userdefObj.unAllotData = JSON.stringify(unAllotData);
		ajax({
			url: url.query_assign_saved,
			data: queryInfo,
			success: (res) => {
				if (res.success) {
					// 设置盘点范围
					this.echartsData.check_range = handleCheck_range.call(
						this,
						res.data.head[area.card.body_head].rows[0].values.check_range.value,
						true
					);
					this.childformData.head = res.data.head[area.card.body_head].rows;
					this.childformData.body = res.data.body[area.card.body_area].rows;
					this.echartsData.start_date = res.data.head[area.card.body_head].rows[0].values.start_date.value;
					this.echartsData.pk_org = res.data.head[area.card.body_head].rows[0].values.pk_org.value;
					this.echartsData.end_date = res.data.head[area.card.body_head].rows[0].values.end_date.value;
					/* 设置图表数据 */
					setEcharsData.call(this, res);
					let current = this.state.current + 1;
					this.setState({ current });
					toggleShow(this, props);
				}
			},
			error: (res) => {
				if (res && res.message) {
					toast({ content: res.message, color: 'danger' });
				}
			}
		});
		// 盘点结果未分配盘点人
	} else if (this.state.current === 7) {
		let tempurl = url.skip_update;
		let updateInfo = getSaveInfo(props);
		updateInfo.head.model.rows = this.childformData.head;
		updateInfo.bodys.bodyvos.rows = this.props.cardTable.getChangedRows(constant.AREA.STEP.ANEWALLOT);
		ajax({
			url: tempurl,
			data: updateInfo,
			success: (res) => {
				this.childformData.head = res.data.head[constant.AREA.CARD.BODY_HEAD].rows;
				this.setState({ current: 7, inventoryStatus: 'confirmed' }, () => {
					toggleShow(this, props);
					loadingResultData.call(this, this.state.pk_inventory);
				});
			},
			error: (res) => {
				if (res && res.message) {
					toast({ content: res.message, color: 'danger' });
				}
			}
		});
	}
}
/* 步骤条下一步按钮 */
export function next() {
	switch (this.state.current) {
		// 第一步选择
		case 0:
			StepOneExcuteNext.call(this);
			break;
		// 第二步选择
		case 1:
			StepTwoExcuteNext.call(this);
			break;
		case 2:
			if (this.state.inventoryStatus) {
				let current = this.state.current + 1;
				this.setState({ current });
			}
			break;
		default:
			break;
	}
}

function StepTwoExcuteNext() {
	// 必输项校验
	if (this.state.inventoryWay != 1) {
		//过滤表格空行
		this.props.editTable.filterEmptyRows(constant.AREA.STEP.ALLOT_CHECKUSER, constant.ALLOT_FILED, 'include');
	}
	let inventoryStatus = this.state.inventoryStatus;
	if (inventoryStatus == 'default' || inventoryStatus == 'noAllot' || inventoryStatus == 'unAllot') {
		//未保存时下一步点击事件
		stepTwoUnSaveExcuteNext.call(this);
	} else {
		//已保存时下一步点击事件
		stepTwoSavedExcuteNext.call(this);
	}
}

function stepTwoSavedExcuteNext() {
	// 有可能是从列表态到重新分配盘点人，那么第二步需要将参数改为false
	this.isFromList = 'false';
	// 分配盘点人中的数据
	let assignTable = [];
	if (this.state.inventoryWay != 1) {
		this.props.editTable.filterEmptyRows(constant.AREA.STEP.ALLOT_CHECKUSER);
		//切换页面会导致editTable的数据清空，在这里缓存
		this.tempEditTableDatas = this.props.editTable.getAllData(constant.AREA.STEP.ALLOT_CHECKUSER);
		if (this.tempEditTableDatas.rows && this.tempEditTableDatas.rows.length > 0) {
			assignTable = this.tempEditTableDatas.rows;
		}
	}
	let tempUrl = url.query_assign_saved;
	// 获取传输的数据
	let queryInfo = {};
	let assignData = getAssignInfo(this.props);
	let tempUserdefObj = {
		// JSON.stringify(assignData);
		pk_inventory: this.state.pk_inventory,
		inventoryWay: '' + this.state.inventoryWay,
		signature: '0'
	};
	queryInfo.userdefObj = tempUserdefObj;
	assignData.model.rows = assignTable;
	queryInfo.userdefObj.assignData = JSON.stringify(assignData);
	ajax({
		url: tempUrl,
		data: queryInfo,
		success: (res) => {
			if (res.data.body[constant.AREA.CARD.BODY_AREA].rows[0].values.inventory_checkuser.value) {
				// 设置资产的数量
				this.echartsData.total_num = res.data.body[area.card.body_area].rows.length;
				// 设置盘点范围
				this.echartsData.check_range = handleCheck_range.call(
					this,
					res.data.head[area.card.body_head].rows[0].values.check_range.value,
					true
				);
				this.echartsData.start_date = res.data.head[area.card.body_head].rows[0].values.start_date.value;
				this.echartsData.end_date = res.data.head[area.card.body_head].rows[0].values.end_date.value;
				this.childformData.head = res.data.head[area.card.body_head].rows;
				this.childformData.body = res.data.body[area.card.body_area].rows;
				// 设置单据号
				this.bill_code = res.data.head[area.card.body_head].rows[0].values.bill_code.value;
				/* 设置图表数据 */
				setEcharsData.call(this, res);
				this.setState({ current: 2, inventoryStatus: 'confirmed' });
				toggleShow(this, this.props);
			} else {
				// 如果有未分配盘点人跳转到分配盘点人页面
				this.signature = '1';
				let inventoryStatus = '';
				if (this.state.inventoryStatus === 'confirmed') {
					inventoryStatus = 'confirmedAllot';
				} else {
					inventoryStatus = 'unAllot';
				}
				this.setState({ current: this.state.current, inventoryStatus }, () => {
					this.props.cardTable.setTableData(
						constant.AREA.STEP.ANEWALLOT,
						res.data.body[constant.AREA.CARD.BODY_AREA]
					);
				});
				this.props.cardTable.setStatus(constant.AREA.STEP.ANEWALLOT, 'edit');
				let that = this;
				toggleShow(that, this.props);
			}
		},
		error: (res) => {
			if (res && res.message) {
				toast({ content: res.message, color: 'danger' });
			}
		}
	});
}

function stepTwoUnSaveExcuteNext() {
	// 分配盘点人中的数据
	let assignTable = [];
	if (this.state.inventoryWay != 1) {
		//过滤空行
		this.props.editTable.filterEmptyRows(constant.AREA.STEP.ALLOT_CHECKUSER);
		//切换页面会导致editTable的数据清空，在这里缓存
		this.tempEditTableDatas = this.props.editTable.getAllData(constant.AREA.STEP.ALLOT_CHECKUSER);
		if (this.tempEditTableDatas.rows && this.tempEditTableDatas.rows.length > 0) {
			assignTable = this.tempEditTableDatas.rows;
		}
	}
	let tempUrl = url.query_assign;
	// 获取传输的数据
	let queryInfo = getQueryInfo(this.props);
	let assignData = getAssignInfo(this.props);
	let tempUserdefObj = {
		// JSON.stringify(assignData);
		inventoryWay: this.state.inventoryWay,
		signature: '0',
		start_date: this.echartsData.start_date,
		end_date: this.echartsData.end_date,
		pk_inventory: this.state.pk_inventory
	};
	queryInfo.userdefObj = tempUserdefObj;
	assignData.model.rows = assignTable;
	queryInfo.userdefObj.assignData = JSON.stringify(assignData);
	ajax({
		url: tempUrl,
		data: queryInfo,
		success: (res) => {
			if (res.data) {
				//没有未分配卡片直接到第三步
				if (res.data.body[constant.AREA.CARD.BODY_AREA].rows[0].values.inventory_checkuser.value) {
					// 设置资产的数量
					this.echartsData.total_num = res.data.body[area.card.body_area].rows.length;
					// 设置盘点范围
					this.echartsData.check_range = handleCheck_range.call(
						this,
						res.data.head[area.card.body_head].rows[0].values.check_range.value,
						true
					);
					this.childformData.head = res.data.head[area.card.body_head].rows;
					this.childformData.body = res.data.body[area.card.body_area].rows;
					/* 设置图表数据 */
					setEcharsData.call(this, res);
					this.setState({ current: 2, inventoryStatus: 'noAllot' });
					toggleShow(this, this.props);
				} else {
					// 如果有未分配盘点人跳转到分配盘点人页面
					this.signature = '1';
					let inventoryStatus = '';
					if (this.state.inventoryStatus === 'confirmed') {
						inventoryStatus = 'confirmedAllot';
					} else {
						inventoryStatus = 'unAllot';
					}
					this.setState({ current: this.state.current, inventoryStatus }, () => {
						this.props.cardTable.setTableData(
							constant.AREA.STEP.ANEWALLOT,
							res.data.body[constant.AREA.CARD.BODY_AREA]
						);
						setTimeout(() => {
							this.props.cardTable.setStatus(constant.AREA.STEP.ANEWALLOT, 'edit');
							this.props.cardTable.setColEditableByKey(
								constant.AREA.STEP.ANEWALLOT,
								'inventory_checkuser',
								false
							);
						}, 0);
					});
					toggleShow(this, this.props);
				}
			}
		},
		error: (res) => {
			if (res && res.message) {
				toast({ content: res.message, color: 'danger' });
			}
		}
	});
}

function StepOneExcuteNext() {
	if (this.props.search.getSearchValByField(constant.AREA.STEP.INVENTORY_RANGE, 'pk_org').value.firstvalue === '') {
		toast({ content: getMultiLangByID('201203004A-000026') /*请选择财务组织！*/, color: 'warning' });
		return;
	} else if (this.props.form.getFormItemsValue(constant.AREA.STEP.INVENTORY_DATE, 'start_date').value === null) {
		toast({ content: getMultiLangByID('201203004A-000027') /*请选择盘点开始日期！*/, color: 'warning' });
		return;
	}
	this.echartsData.start_date = this.props.form.getAllFormValue(
		constant.AREA.STEP.INVENTORY_DATE
	).rows[0].values.start_date.value;
	this.echartsData.end_date = this.props.form.getAllFormValue(
		constant.AREA.STEP.INVENTORY_DATE
	).rows[0].values.end_date.value;
	if (this.echartsData.end_date != null) {
		if (this.echartsData.end_date < this.echartsData.start_date) {
			toast({ content: getMultiLangByID('201203004A-000028') /*盘点结束日期不能早于盘点开始日期！*/, color: 'warning' });
			return;
		}
	}
	this.rangeAreaData = this.props.search.getAllSearchData(constant.AREA.STEP.INVENTORY_RANGE);
	this.dateAreaData = this.props.form.getAllFormValue(constant.AREA.STEP.INVENTORY_DATE);
	this.echartsData.search_range = this.props.search.getAllSearchData(constant.AREA.STEP.INVENTORY_RANGE);
	this.echartsData.pk_org = this.props.search.getAllSearchData(constant.AREA.STEP.INVENTORY_RANGE).conditions[0];
	let searchqueryInfo = this.props.search.getQueryInfo(constant.AREA.STEP.INVENTORY_RANGE);
	// 获取传输的数据
	let queryInfo = getQueryInfo(this.props);
	let tempUserdefObj = {
		inventoryWay: this.state.inventoryWay,
		signature: '5',
		start_date: this.echartsData.start_date
	};
	queryInfo.userdefObj = tempUserdefObj;
	ajax({
		url: url.query_assign,
		data: queryInfo,
		success: (res) => {
			if (res.data) {
				if (res.data.total != 0) {
					let that = this;
					//切换按钮状态
					toggleShow(that, this.props);
					this.echartsData.total_num = res.data.total;
					let current = 1;
					this.setState({ current });
					this.signature = 0;
				} else {
					toast({ content: getMultiLangByID('201203004A-000029') /*盘点范围内不存在任何资产!*/, color: 'warning' });
				}
			}
		},
		error: (res) => {
			if (res && res.message) {
				toast({ content: res.message, color: 'danger' });
			}
		}
	});
}
/* 保存单击事件 */
export function save(props) {
	let current = this.state.current;
	if (current == 2) {
		stepTreeExcuteSave.call(this, props);
		// 穿透列表保存
	} else if (current == 6) {
		throughAreaExcuteSave.call(this, props);
	}
}

function throughAreaExcuteSave(props) {
	props.cardTable.filterEmptyRows(
		constant.AREA.STEP.DETAIL_LIST,
		[ 'asset_name', 'pk_category', 'card_num_after', 'check_result' ],
		'include'
	);

	//由于返回值只处理盘盈的数据，所以每次保存时都将盘盈数据发到后台，为了能有返回值
	let bodyDatas = this.props.cardTable.getAllData(constant.AREA.STEP.DETAIL_LIST);
	let bodyRows = bodyDatas.rows;
	bodyRows.map((item) => {
		//先判断是否有盘盈数据
		if (item.values.check_result.value == 1) {
			if (item.status == 0) {
				item.status = 1; //为了getChangeRows能够获取到
			}
		}
	});

	//校验表体必输项
	let detailData = this.props.cardTable.getChangedRows(constant.AREA.STEP.DETAIL_LIST);
	let errorMessage = '';
	for (let index = 0; index < detailData.length; index++) {
		// 如果是未处理不进行校验
		if (detailData[index].values.check_result.value == null || detailData[index].values.check_result.value == '') {
			continue;
		}
		// 如果是盘亏或者未盘不进行校验
		if (detailData[index].values.check_result.value == 2) {
			continue;
		}
		// 如果是盘盈数据--只校验资产名称和盘点后数量，并且盘点后数量大于等于1
		if (detailData[index].values.check_result.value == 1) {
			if (detailData[index].values.asset_name.value == null || detailData[index].values.asset_name.value == '') {
				errorMessage +=
					getMultiLangByID('201203004A-000054', {
						index: detailData[index].values.numberindex.value
					}) /*第{index}行盘点后资产名称为空*/ + '\\n';
			}
			if (
				detailData[index].values.card_num_after.value == null ||
				detailData[index].values.card_num_after.value == ''
			) {
				errorMessage +=
					getMultiLangByID('201203004A-000056', {
						index: detailData[index].values.numberindex.value
					}) /*第{index}行盘点后数量为空*/ + '\\n';
			} else {
				if (parseInt(detailData[index].values.card_num_after.value) < 1) {
					errorMessage +=
						getMultiLangByID('201203004A-000057', {
							index: detailData[index].values.numberindex.value
						}) /*第{index}行盘点后数量不能小于1*/ + '\\n';
				}
			}

			continue;
		}
		//先判断使用部门编码是否显示，显示在判断是否为空
		let meta = this.props.meta.getMeta();
		let isShowUsedept = false;
		let isShowMandept = false;
		let isUsingstatus = false;
		if (
			meta &&
			meta[constant.AREA.STEP.DETAIL_LIST] &&
			meta[constant.AREA.STEP.DETAIL_LIST].items &&
			meta[constant.AREA.STEP.DETAIL_LIST].items.length > 0
		) {
			meta[constant.AREA.STEP.DETAIL_LIST].items.map((item) => {
				if (item.attrcode == 'pk_usedept_after_v' && item.visible == true) {
					isShowUsedept = true;
				}
				if (item.attrcode == 'pk_usedept_after' && item.visible == true) {
					isShowUsedept = true;
				}
				if (item.attrcode == 'pk_mandept_after_v' && item.visible == true) {
					isShowMandept = true;
				}
				if (item.attrcode == 'pk_mandept_after' && item.visible == true) {
					isShowMandept = true;
				}
				if (item.attrcode == 'pk_usingstatus_after' && item.visible == true) {
					isUsingstatus = true;
				}
			});
		}
		if (
			isShowUsedept &&
			(detailData[index].values.pk_usedept_after_v.value == null ||
				detailData[index].values.pk_usedept_after_v.value == '')
		) {
			errorMessage += getMultiLangByID('201203004A-000058', { index: index + 1 }) /*第{index}行盘点后使用部门为空*/ + '\\n';
		}
		if (
			isUsingstatus &&
			(detailData[index].values.pk_usingstatus_after.value == null ||
				detailData[index].values.pk_usingstatus_after.value == '')
		) {
			errorMessage += getMultiLangByID('201203004A-000031', { index: index + 1 }) /*第{index}行盘点后使用状况为空*/ + '\\n';
		}
		if (
			isShowMandept &&
			(detailData[index].values.pk_mandept_after_v.value == null ||
				detailData[index].values.pk_mandept_after_v.value == '')
		) {
			errorMessage += getMultiLangByID('201203004A-000032', { index: index + 1 }) /*第{index}行盘点后管理部门为空*/ + '\\n';
		}
	}
	if (errorMessage.length != 0) {
		toast({
			content: errorMessage,
			color: 'danger',
			isNode: true,
			duration: 10
		});
		return;
	}
	// 穿透表体数据
	let tempurl = url.skip_update;
	let updateInfo = getSaveInfo(props);
	updateInfo.head.model.rows = this.childformData.head;
	//需要将审批未通过的状态改为自由态
	if (
		updateInfo.head.model.rows[0].values.bill_status &&
		updateInfo.head.model.rows[0].values.bill_status.value &&
		updateInfo.head.model.rows[0].values.bill_status.value == '4'
	) {
		updateInfo.head.model.rows[0].values.bill_status.value = '0';
		if (updateInfo.head.model.rows[0].status == 0) {
			updateInfo.head.model.rows[0].status = 1;
		}
	}
	updateInfo.bodys.bodyvos.rows = this.props.cardTable.getChangedRows(constant.AREA.STEP.DETAIL_LIST);
	const validateData = {
		pageid: pagecode,
		model: {
			areaType: 'table',
			areacode: constant.AREA.STEP.DETAIL_LIST,
			rows: detailData
		}
	};
	this.props.validateToSave(validateData, () => {
		ajax({
			url: tempurl,
			data: updateInfo,
			success: (res) => {
				// 盘点范围多语显示处理
				handleCheck_range.call(
					this,
					res.data.head[constant.AREA.CARD.BODY_HEAD].rows[0].values.check_range,
					true
				);
				this.childformData.head = res.data.head[constant.AREA.CARD.BODY_HEAD].rows;
				let inventoryStatus = 'confirmed';
				this.ts = res.data.head[constant.AREA.CARD.BODY_HEAD].rows[0].values.ts.value;
				let pk = res.data.head.card_head.rows[0].values.pk_inventory.value;
				this.props.setUrlParam({ id: pk });
				let i = 0;
				let newRows = [];
				//处理返回数据
				bodyRows.map((item) => {
					if (item.status == VOSTATUS.UPDATED || item.status == VOSTATUS.NEW) {
						if (res.data.body && res.data.body[constant.AREA.STEP.DETAIL_LIST]) {
							let resRows = res.data.body[constant.AREA.STEP.DETAIL_LIST].rows;
							newRows.push(resRows[i]);
						}
						i++;
					} else {
						newRows.push(item);
					}
				});
				bodyDatas.rows = newRows;

				this.props.cardTable.setTableData(constant.AREA.STEP.DETAIL_LIST, bodyDatas);
				//更新缓存
				cardCache.updateCache('pk_inventory', pk, res.data, constant.AREA.CARD.BODY_HEAD, constant.DATASOURCE);
				let that = this;
				this.setState({ inventoryStatus }, () => {
					setTimeout(() => {
						props.cardTable.setStatus(constant.AREA.STEP.DETAIL_LIST, 'browse');
					}, 0);
					toggleShow(that, props);
				});
			},
			error: (res) => {
				if (res && res.message) {
					toast({ content: res.message, color: 'danger' });
				}
			}
		});
	});
}

function stepTreeExcuteSave(props) {
	//获取表头和表体信息
	let saveInfo = getSaveInfo(props);
	// 交易类型
	let transi_type = getContext(loginContextKeys.transtype);
	// 交易类型主键
	let pk_transi_type = getContext(loginContextKeys.pk_transtype);
	// 报告日期
	let businessDate = '';
	if (this.echartsData.end_date) {
		businessDate = this.echartsData.end_date;
	} else {
		businessDate = getContext(loginContextKeys.businessDate);
	}
	// 盘点方式
	// 分配盘点人中的数据
	let invent_way = this.state.inventoryWay;
	let inventoryWay = '';
	if (this.state.inventoryWay != 1) {
		if (this.tempEditTableDatas.rows && this.tempEditTableDatas.rows.length > 0) {
			inventoryWay = this.tempEditTableDatas.rows;
		}
		//先判断盘点方式是否有值，如果没有，则换成默认盘点方式
		if (inventoryWay == null || inventoryWay == '' || inventoryWay.length <= 0) {
			inventoryWay = [
				{
					values: {
						inventoryway: {
							display: null,
							scale: null,
							value: '1'
						}
					}
				}
			];
			this.state.inventoryWay = 1;
		} else {
			for (const key in inventoryWay) {
				inventoryWay[key].values.inventoryway.value = invent_way + '';
			}
		}
		// 使用人盘点
	} else {
		inventoryWay = [
			{
				values: {
					inventoryway: {
						display: null,
						scale: null,
						value: '1'
					}
				}
			}
		];
	}
	this.childformData.head[0].values.inventoryway.value = '' + this.state.inventoryWay;
	this.childformData.head[0].values.transi_type.value = transi_type;
	this.childformData.head[0].values.business_date.value = businessDate;
	this.childformData.head[0].values.bill_type.value = constant.BILL_TYPE;
	this.childformData.head[0].values.pk_transitype.value = pk_transi_type;
	//保存前校验下盘点范围的长度，如果超长则截取掉
	let check_range = this.childformData.head[0].values.check_range;
	//盘点范围多语保存
	handleCheck_range.call(this, check_range);
	if (check_range.value != null && check_range.value.length > constant.CHECK_RANGE_LENGTH) {
		this.childformData.head[0].values.check_range.value =
			check_range.value.substring(0, constant.CHECK_RANGE_LENGTH) + '...';
	}
	saveInfo.head.model.rows = this.childformData.head;
	saveInfo.bodys.bodyvos.rows = this.childformData.body;
	saveInfo.bodys.tableArea2.rows = inventoryWay;
	let tempurl = url.save;
	if (this.state.inventoryStatus === 'confirmedAllot' || this.state.inventoryStatus === 'confirmed') {
		tempurl = url.update;
	}
	ajax({
		url: tempurl,
		data: JSON.stringify(saveInfo),
		success: (res) => {
			this.childformData.head = res.data.head.card_head.rows;
			// this.childformData.body = res.data.body.bodyvos.rows;
			this.bill_code = res.data.head.card_head.rows[0].values.bill_code.value;
			// 盘点范围多语显示处理
			handleCheck_range.call(this, res.data.head.card_head.rows[0].values.check_range, true);
			this.echartsData.check_range = res.data.head.card_head.rows[0].values.check_range.value;
			let pk = res.data.head.card_head.rows[0].values.pk_inventory.value;
			this.props.setUrlParam({ id: pk });
			// 保存成功后处理缓存
			if (this.state.inventoryStatus === 'confirmedAllot' || this.state.inventoryStatus === 'confirmed') {
				cardCache.updateCache('pk_inventory', pk, res.data, constant.AREA.CARD.BODY_HEAD, constant.DATASOURCE);
			} else {
				cardCache.addCache(pk, res.data, constant.AREA.CARD.BODY_HEAD, constant.DATASOURCE);
			}
			loadingResultData.call(this, pk);
			let showdata = { status: 'browse', bill_code: this.bill_code };
			setHeadAreaData.call(this, this.props, showdata);
			//setTitleData.call(this, { status: 'browse', bill_code: this.bill_code });
			this.setState({ pk_inventory: pk }, () => {
				toggleShow(this, props);
			});
		},
		error: (res) => {
			if (res && res.message) {
				toast({ content: res.message, color: 'danger' });
			}
		}
	});
}

/* 步骤条“重新分配盘点人” 按钮 */
function allotAgain(props) {
	let { cardTable } = this.props;
	let current = 1;
	let inventoryStatus = 'confirmed';
	let queryInfo = {};
	let tempUserdefObj = {
		pk_inventory: this.state.pk_inventory,
		signature: '7',
		inventoryWay: 1
	};
	// 把盘点的柱状图数据清空
	this.echartsData.linedata.data = [];
	this.echartsData.linedata.name = [];
	queryInfo.userdefObj = tempUserdefObj;
	ajax({
		url: url.query_assign_saved,
		data: queryInfo,
		success: (res) => {
			if (res.data) {
				if (res.data.total == 'null') {
					toast({ content: getMultiLangByID('201203004A-000034') /*所有资产已盘点完毕，不支持重新分配！*/, color: 'warning' });
				} else {
					this.setState({ current, inventoryStatus }, () => {
						editTable.setStatus(constant.AREA.STEP.ALLOT_CHECKUSER, 'edit');
						let that = this;
						toggleShow(that, props);
					});
				}
			}
		},
		error: (res) => {
			if (res && res.message) {
				toast({ content: res.message, color: 'danger' });
			}
		}
	});
}
/* 步骤条中   “重新分配” 按钮 */
function reInventory(props) {
	let inventoryStatus = this.state.inventoryStatus;
	if (inventoryStatus == 'confirmedAllot') {
		inventoryStatus = 'confirmed';
	}
	if (inventoryStatus == 'unAllot') {
		inventoryStatus = 'default';
	}
	this.setState({ current: 1, inventoryStatus: inventoryStatus });
	props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_HALF_BTNS, false);
	props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_BTNS, true);
}
/* 步骤条中   “上一步” 按钮 */
function prev(props) {
	let inventoryStatus = this.state.inventoryStatus;
	if (inventoryStatus == 'confirmed' || inventoryStatus == 'confirmedAllot') {
		toast({ content: getMultiLangByID('201203004A-000035') /*允许重新分配盘点人，但不允许修改盘点范围！*/, color: 'warning' });
	} else {
		this.setState({ current: 0 });
		props.form.setAllFormValue({ childform2: this.dateAreaData });
		props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_BTNS, false);
		props.button.setButtonVisible(constant.STEP_BTNS.STEP_ONE_BTNS, true);
	}
}
/* 默认加载盘点结果数据 */
export function loadingResultData(pk, callBack) {
	let queryInfo = {
		pk: pk
	};
	ajax({
		url: url.query_inventory_result,
		data: queryInfo,
		success: (res) => {
			// 插入前先置空数据
			this.echartsData.bar_data.x_axis = [];
			this.echartsData.bar_data.unfinished = [];
			this.echartsData.bar_data.finished = [];
			let arr = new Array();
			let result_category = [
				getMultiLangByID('201203004A-000004') /*未盘*/,
				getMultiLangByID('201203004A-000036') /*相符*/,
				getMultiLangByID('201203004A-000037') /*不符*/,
				getMultiLangByID('201203004A-000038') /*盘盈*/,
				getMultiLangByID('201203004A-000039') /*盘亏*/,
				getMultiLangByID('201203004A-000040') /*全部*/,
				getMultiLangByID('201203004A-000051') /*不符+盘盈+盘亏*/
			];
			for (let key in res.data) {
				let stage = new Array();
				let pie_values = new Array();
				var obj = eval('(' + key + ')');
				// 获取表头数据
				this.childformData.head = obj;
				let temp_arr = obj.def1.split('-');
				for (let temp of temp_arr) {
					arr.push(Number(temp));
				}
				arr.push(arr[0] + arr[1] + arr[2] + arr[3] + arr[4]);
				arr.push(arr[2] + arr[3] + arr[4]);
				for (let index = 0; index < result_category.length; index++) {
					pie_values.push({
						value: arr[index]
					});
				}
				pie_values[5].value = arr[7];
				pie_values[6].value = arr[8];
				// 饼图数据
				this.echartsData.total_num = arr[7];
				this.echartsData.pie_data.category_total = stage;
				this.echartsData.pie_data.values = pie_values;
				// 柱状图数据
				let result_arr = res.data[key];
				if (result_arr.length != 0) {
					for (var j = 0, len = result_arr.length; j < len; j++) {
						this.echartsData.bar_data.x_axis.push(result_arr[j].userName),
							this.echartsData.bar_data.unfinished.push(result_arr[j].unfinished);
						this.echartsData.bar_data.finished.push(result_arr[j].finished);
					}
				}
				// 如果有未分配人员，把未分配人员放到第一个
				if (arr[5] != 0 || arr[6] != 0) {
					this.echartsData.bar_data.x_axis.unshift(getMultiLangByID('201203004A-000006') /*未分配人员*/);
					this.echartsData.bar_data.unfinished.unshift(arr[6]);
					this.echartsData.bar_data.finished.unshift(arr[5]);
				}
				// 时间戳赋值
				this.ts = obj.ts;

				// 设置 saga 按钮状态
				let saga_status = obj.saga_status;
				let isError = SagaStatus.errorValue === saga_status;
				this.setState({
					billInfo: {
						isError,
						gtxid: obj.saga_gtxid,
						billpk: obj[pkField],
						billtype: constant.BILL_TYPE
					}
				});
				if (isError) {
					//满足条件弹出错误提示框
					this.props.socket &&
						this.props.socket.showToast &&
						this.props.socket.showToast({
							gtxid: obj.saga_gtxid,
							billpk: obj[pkField]
						});
				}
			}
			// 处理盘点范围多语
			this.childformData.head.check_range = handleCheck_range.call(
				this,
				this.childformData.head.check_range,
				true
			);

			let bill_code = this.childformData.head.bill_code;
			let bill_status = this.childformData.head.bill_status;
			this.bill_code = bill_code;
			this.setState(
				{
					current: 7,
					inventoryStatus: 'confirmed',
					pk_inventory: pk,
					// bill_code: bill_code,
					bill_status: bill_status
				},
				() => {
					toggleShow(this, this.props);
				}
			);
			let showdata = { status: 'browse', bill_code: this.bill_code };
			setHeadAreaData.call(this, this.props, showdata);
			//setTitleData.call(this, { status: 'browse', bill_code: bill_code });
			callBack && typeof callBack == 'function' && callBack.call(this);
		},
		error: (res) => {
			if (res && res.message) {
				toast({ content: res.message, color: 'danger' });
			}
		}
	});
}
/* 穿透列表点击事件 */
export function skipClick(index, that) {
	let pk_inventory = that.state.pk_inventory;
	let result_category = index;
	let current = 6;
	let inventoryStatus = 'confirmed';
	if (that.state.bill_status != '0' && that.state.bill_status != '4') {
		inventoryStatus = 'browse';
	}
	let { cardTable } = that.props;
	that.checkResult = index;
	let queryInfo = {};
	let tempUserdefObj = {
		check_result: result_category == null ? 0 : result_category,
		pk_inventory: pk_inventory
	};
	queryInfo.userdefObj = tempUserdefObj;
	ajax({
		url: url.query_check_result,
		data: queryInfo,
		success: (res) => {
			if (res.data.head != null) {
				that.echartsData.pk_org = res.data.head[constant.AREA.CARD.BODY_HEAD].rows[0].values.pk_org.value;
				that.childformData.head = res.data.head[constant.AREA.CARD.BODY_HEAD].rows;
			}
			if (res.data.body != null) {
				that.setState({ current, inventoryStatus }, () => {
					toggleShow(that, that.props);
				});
				setTimeout(() => {
					cardTable.setTableData(
						constant.AREA.STEP.DETAIL_LIST,
						res.data.body[constant.AREA.CARD.BODY_AREA],
						null,
						true,
						true
					);
					cardTable.setStatus(constant.AREA.STEP.DETAIL_LIST, 'browse');
				}, 0);
			} else {
				that.setState({ current, inventoryStatus }, () => {
					toggleShow(that, that.props);
				});
				setTimeout(() => {
					cardTable.setTableData(constant.AREA.STEP.DETAIL_LIST, { rows: [] });
					cardTable.setStatus(constant.AREA.STEP.DETAIL_LIST, 'browse');
				}, 0);
			}
		},
		error: (res) => {
			if (res && res.message) {
				toast({ content: res.message, color: 'danger' });
			}
		}
	});
}
/* 获取盘点方式 */
export function queryInventoryWay(pk) {
	ajax({
		url: url.query_inventory_way,
		data: { pk: pk },
		success: (res) => {
			if (res.data) {
				let inventoryWay = res.data.head['card_head'].rows[0].values.inventoryway.value;
				// 以前在保存盘点方式时，没有考虑到非默认方式清空表体的情况，在这加个判断
				if (inventoryWay == undefined || inventoryWay == null || inventoryWay == '') {
					inventoryWay = 1; //默认方式
				}
				this.setState({ inventoryWay: inventoryWay }, () => {
					if (inventoryWay != 1 && res.data.bodys) {
						this.props.editTable.setTableData(
							constant.AREA.STEP.ALLOT_CHECKUSER,
							res.data.bodys[constant.AREA.STEP.ALLOT_CHECKUSER]
						);
						this.isHint = false;
					}
				});
				changeItem.call(this, inventoryWay);
			}
		},
		error: (res) => {
			if (res && res.message) {
				toast({ content: res.message, color: 'danger' });
			}
		}
	});
}
/* 修改点击事件 */
function editAction(props) {
	let pk = props.getUrlParam('id');
	ajax({
		url: url.edit,
		data: {
			pk,
			resourceCode: '2012048020'
		},
		success: (res) => {
			if (res.data) {
				toast({ color: 'danger', content: res.data });
			} else {
				this.setState({ inventoryStatus: 'edit' }, () => {
					this.props.cardTable.setStatus(constant.AREA.STEP.DETAIL_LIST, 'edit');
					toggleShow(this, props);
				});
			}
		}
	});
}

/**
* 取消
* @param {*} props 
*/
export function cancel(props) {
	if (this.state.inventoryStatus == 'edit') {
		showConfirm.call(this, props, {
			type: MsgConst.Type.Cancel,
			beSureBtnClick: (props) => {
				this.setState({ current: 6, inventoryStatus: 'confirmed' }, () => {
					toggleShow(this, props);
					this.props.cardTable.resetTableData(constant.AREA.STEP.DETAIL_LIST);
				});
			}
		});
	} else {
		props.ncmodal.show(`${pagecode}-confirm`, {
			title: getMultiLangByID('msgUtils-000002') /* 国际化处理：取消 */,
			content: getMultiLangByID('201203004A-000042') /*确定要取消当前操作信息，返回列表？*/,
			beSureBtnClick: () => {
				this.setState({ current: 0, inventoryStatus: 'default' });
				this.props.editTable.setStatus(constant.AREA.STEP.ALLOT_CHECKUSER, 'browse');
				this.state.isLeaveOrRefresh = false;
				linkToList.call(this, props, undefined, 'add');
			}
		});
	}
}
/**
 * 跳转列表
 * @param {*} props 
 * @param {*} record 
 */
export function linkToList(props, record = {}, status = 'browse') {
	props.pushTo(listRouter, {
		pagecode: pagecode.replace('card', 'list')
	});
}
/**
* 返回
* @param {*} props 
*/
export function backToList(props) {
	if (this.state.current == 7) {
		if (this.state.inventoryStatus == 'confirmedAllot') {
			this.setState({ current: 7 }, () => {
				loadingResultData.call(this, this.state.pk_inventory);
			});
		} else {
			// 避免盘点结果未分配界面计划盘点人参照传值错误，确认后清空组织
			this.result_pk_org = '';
			props.pushTo(listRouter, {
				pagecode: pagecode.replace('card', 'list')
			});
		}
	} else if (this.state.current == 6) {
		this.props.cardTable.closeExpandedRow(constant.AREA.STEP.DETAIL_LIST);
		this.setState({ current: 7 }, () => {
			loadingResultData.call(this, this.state.pk_inventory);
		});
	} else {
		props.pushTo(listRouter, {
			pagecode: pagecode.replace('card', 'list')
		});
	}
}
/**
* 新增行
* @param {*} props 
*/
export function addLine(props) {
	// let userid = getContext(loginContextKeys.userId);
	// let userName = getContext(loginContextKeys.userName);
	let numberOfRows = this.props.cardTable.getNumberOfRows(constant.AREA.STEP.DETAIL_LIST, false);
	// 增行的都是盘盈的卡片
	props.cardTable.addRow(constant.AREA.STEP.DETAIL_LIST, numberOfRows, {
		check_result: {
			display: getMultiLangByID(constant.CHECK_RESULT.PROFIT.display),
			value: constant.CHECK_RESULT.PROFIT.value
		},
		card_num_after: { display: '1', value: '1' },
		// inventory_checkuser: { display: userName, value: userid },
		// checkuser_name: { display: userName, value: userName },
		pk_inventory: {
			display: this.childformData.head.pk_inventory,
			value: this.childformData.head.pk_inventory
		}
	});
	// 新增行类别名称可以编辑
	setTimeout(() => {
		props.cardTable.setEditableByIndex(constant.AREA.STEP.DETAIL_LIST, 0, 'asset_name', true);
		props.cardTable.setEditableByIndex(constant.AREA.STEP.DETAIL_LIST, 0, 'pk_category', true);
	}, 0);
}
/**
 * 通过单据id获取缓存单据信息，没有缓存则重新查询
 * @param {*} props 
 * @param {*} pk 
 */
export function loadDataByPk(props, pk) {
	if (!pk || pk == 'null') {
		return;
	}
	let cachData = cardCache.getCacheById(pk, dataSource);
	if (cachData) {
		// setValue.call(this, props, cachData);
	} else {
		getDataByPk.call(this, props, pk);
	}
}
/**
 * 通过单据id查询单据信息
 * @param {*} props 
 * @param {*} pk 
 */
export function getDataByPk(props, pk) {
	ajax({
		url: url.queryCardUrl,
		data: {
			pagecode,
			pk
		},
		success: (res) => {
			let { success, data } = res;
			if (success) {
				if (data) {
					// setValue.call(this, props, data);
					cardCache.updateCache(pkField, pk, data, formId, dataSource);
				} else {
					// setValue.call(this, props, undefined);
					cardCache.deleteCacheById(pkField, pk, dataSource);
					showMessage.call(this, props, { type: MsgConst.Type.DataDeleted });
				}
			}
		},
		error: (res) => {
			if (res && res.message) {
				toast({ content: res.message, color: 'danger' });
			}
		}
	});
}
/* 获取前后台传输对象 */
// 查询条件
function getQueryInfo(props) {
	let queryInfo = props.search.getQueryInfo(constant.AREA.STEP.INVENTORY_RANGE);
	// 分页信息
	let pageInfo = {
		pageIndex: 0,
		pageSize: 10,
		total: 0,
		totalPage: 0
	};
	queryInfo.pageInfo = pageInfo;
	queryInfo.pagecode = pagecode;
	queryInfo.billtype = bill_type;
	queryInfo.transtype = transi_type;

	return queryInfo;
}
/* 未分配盘点人页面数据 */
function getUnAllotInfo(props) {
	let unAllotData = {
		pageid: '201203004A_card',
		model: {
			areaType: 'table',
			areacode: constant.AREA.STEP.ANEWALLOT,
			rows: []
		}
	};
	return unAllotData;
}
/* 未分配盘点人页面数据 */
function getAssignInfo(props) {
	let assignData = {
		pageid: '201203004A_card',
		model: {
			areaType: 'table',
			areacode: constant.AREA.STEP.ALLOT_CHECKUSER,
			rows: []
		}
	};
	return assignData;
}
/* 要保存的数据 */
function getSaveInfo(props) {
	let doneData = {
		head: {
			model: {
				areaType: 'form',
				areacode: 'card_head',
				pageInfo: {
					pageIndex: '',
					pageSize: '',
					total: '',
					totalPage: ''
				},
				rows: []
			},
			pageid: '201203004A_card'
		},
		bodys: {
			bodyvos: {
				areaType: 'table',
				areacode: 'bodyvos',
				pageInfo: {
					pageIndex: '',
					pageSize: '',
					total: '',
					totalPage: ''
				},
				rows: []
			},
			tableArea2: {
				areaType: 'table',
				areacode: 'tableArea2',
				rows: []
			}
		},

		pageid: '201203004A_card'
	};
	return doneData;
}
/**
 * 附件管理
 * @param {*} props 
 */
function attachment(props) {
	// billId 是单据主键
	let billId = this.state.pk_inventory;
	props.ncUploader.show(`${pagecode}-uploader`, { billId: 'fa/inventory/' + billId });
}
/**
 * 批改
 * @param {*} props 
 */
export function batchAlterAction() {
	// 获取原始数据
	//let changeData = this.props.cardTable.getTableItemData(constant.AREA.STEP.ANEWALLOT);
	// if (changeData.batchChangeKey == 'inventory_checkuser') {
	// 	// 如果需要批改的字段只是简单的赋值操作，则走前台的批改操作
	// 	this.props.cardTable.batchChangeTableData(constant.AREA.STEP.ANEWALLOT);
	// }
	this.props.cardTable.batchChangeTableData(constant.AREA.STEP.ANEWALLOT);
}
/* 把对象里的属性排序 */
function sortFun(obj, str = getMultiLangByID('201203004A-000006') /*未分配人员*/) {
	let newObj = {}; //排好序的新的对象
	let keys = Object.keys(obj); //获取obj对象的属性集合，是个数组
	if (keys.join('').indexOf(str) > -1) {
		//排除掉‘未分配人员’
		newObj[str] = obj[str];
		delete obj[str];
	}
	let values = Object.values(obj); //获取obj对象的属性值集合，是个数组
	values.sort((a, b) => {
		return b - a;
	}); //对数组进行降序排序
	for (let i = 0; i < values.length; i++) {
		//按照属性值对对象进行排序
		for (let key in obj) {
			if (values[i] == obj[key]) {
				newObj[key] = values[i];
			}
		}
	}
	return newObj;
}
/**
 * 给盘点确认以及确认后图表赋值
 */
function setEcharsData(res) {
	let linedataSource = res.data.body[area.card.body_area].rows;
	let arr = {};
	let pk_name = {};
	let first = getMultiLangByID('201203004A-000006') /*未分配人员*/;
	pk_name[first] = getMultiLangByID('201203004A-000006') /*未分配人员*/;
	linedataSource.map((value) => {
		// 把主键和当前人员盘点的数量都放到对象中
		if (value.values.inventory_checkuser.value) {
			let pk = value.values.inventory_checkuser.value;
			let name = value.values.inventory_checkuser.display;
			if (!arr[pk]) {
				arr[pk] = 1;
				pk_name[pk] = name;
			} else {
				arr[pk] += 1;
			}
		} else {
			let unallot_name = getMultiLangByID('201203004A-000006') /*未分配人员*/;
			if (!arr[unallot_name]) {
				arr[unallot_name] = 1;
			} else {
				arr[unallot_name] += 1;
			}
		}
	});
	// 插入前先置空数据
	this.echartsData.linedata.name = [];
	this.echartsData.linedata.data = [];
	// 数据排序
	let sort_data = sortFun(arr);
	for (let key in sort_data) {
		if (key == getMultiLangByID('201203004A-000006') /*未分配人员*/) {
		}
		this.echartsData.linedata.name.push(pk_name[key]);
		this.echartsData.linedata.data.push(sort_data[key]);
	}
}
/* 全部相符 */
function allMatch(props) {
	let result = this.props.cardTable.getVisibleRows(constant.AREA.STEP.DETAIL_LIST);
	if (result == null) {
		return;
	}
	// 先收集所有的pk_card，调用后台查询使用部门信息
	let pk_cards = [];
	for (let index = 0; index < result.length; index++) {
		if (result[index].values.check_result.value == 1) {
			continue;
		}
		pk_cards.push(result[index].values.pk_card.value);
	}
	if (pk_cards.length > 0) {
		let data = {
			allpks: pk_cards
		};
		ajax({
			url: url.query_cardmessage,
			data: data,
			success: (res) => {
				let { success, data } = res;
				if (success) {
					if (data) {
						for (let index = 0; index < result.length; index++) {
							// 盘盈卡片不进行相符操作
							if (result[index].values.check_result.value == 1) {
								continue;
							} else {
								let deptScaleVO = data[result[index].values.pk_card.value];
								let pk_usedept_after_value = '';
								let pk_usedept_after_v_value = '';
								let pk_usedept_after_name = '';
								if (deptScaleVO) {
									if (deptScaleVO.pk_dept) {
										pk_usedept_after_value = deptScaleVO.pk_dept;
									}
									if (deptScaleVO.pk_dept_v) {
										pk_usedept_after_v_value = deptScaleVO.pk_dept_v;
									}
									if (deptScaleVO.deptName) {
										pk_usedept_after_name = deptScaleVO.deptName;
									}
								}
								setOrgInventoryAttribute(
									this.props,
									result[index],
									index,
									pk_usedept_after_value,
									pk_usedept_after_v_value,
									constant.AREA.STEP.DETAIL_LIST,
									pk_usedept_after_name
								);
								this.props.cardTable.setValByKeysAndIndex(constant.AREA.STEP.DETAIL_LIST, index, {
									// 数量
									card_num_after: {
										display: result[index].values.card_num_before.display,
										value: result[index].values.card_num_before.value
									},

									// 盘点结果
									check_result: {
										display: getMultiLangByID(constant.CHECK_RESULT.EQUAL.display),
										value: constant.CHECK_RESULT.EQUAL.value
									}
								});
							}
						}
					}
				}
			}
		});
	}
}

/* 导入 */
function Import(props) {
	document.querySelector('#fileInfo').click();
	
}

export function importSuccess(retdata) {

	let result = this.props.cardTable.getVisibleRows(constant.AREA.STEP.DETAIL_LIST);
	if (result == null) {
		return;
	}

	for (let index = 0; index < result.length; index++) {
		let id= result[index].values['asset_code'].value;//行资产编码

		let rdataRow = findDataById(id, retdata);//得到execl里的具体数据
		if(rdataRow != NaN){
			putRowValues.call(this, index, rdataRow);
		}
	}

	toast({ content: '导入成功', color: 'success' });
}

/* 导出 */
function Export(props) {
	let data = getExcelExportData(props);

	formDownload({
			params:data,
            url:'/nccloud/fa/orginventory/excelExport.do',
            enctype:2
	});
	toast({ content: '导出成功', color: 'success' });
}

function findDataById(id, retdata){
	let result = NaN;

	for (let index = 0; index < retdata.length; index++) {
		if(id == retdata[index].asset_code.value){
			result = retdata[index];
			break;
		}
	}

	return result;
}

function putRowValues(index, rdataRow){
	let props = this.props;

	let keys = Object.keys(rdataRow);

	for(let i = 0; i < keys.length; i++){
		let key = keys[i];
		if(isNeed(props, key)){
			let value = rdataRow[key].value;
			let display = rdataRow[key].display;
			setValueByIndex.call(this, props, key, value, display, index);

			if('pk_mandept_after' == key){
				let VKey = 'pk_mandept_after_v';
				let Vvalue = rdataRow[VKey].value;
				let Vdisplay = rdataRow[VKey].display;
				setValueByIndex.call(this, props, VKey, Vvalue, Vdisplay, index);
			}else if('pk_usedept_after' == key){
				let VKey = 'pk_usedept_after_v';
				let Vvalue = rdataRow[VKey].value;
				let Vdisplay = rdataRow[VKey].display;
				setValueByIndex.call(this, props, VKey, Vvalue, Vdisplay, index);
			}

		}
	}

	// setValueByIndex.call(this, props, 'card_num_after', '1', '1', index);
	// setValueByIndex.call(this, props, 'pk_usingstatus_after', '0001V110000000000Y5H', '运行', index);
	// setValueByIndex.call(this, props, 'pk_mandept_after', '0001V1100000000016UA', '生产类-镀铬-镀铬公共', index);
}

function isNeed(props, key){

	let result = false;

	//特殊字段不处理
	if(key == 'pk_category') {
		return result;
	}


	let items = props.meta.getMeta()[constant.AREA.STEP.DETAIL_LIST].items;//所有列
	for(let i = 0; i < items.length; i ++){
		if(key == items[i].attrcode){

			if(items[i].visible == true && items[i].disabled == false){
				result = true;
			}

			break;
		}
	}

	return result;
}

function setValueByIndex(props, key, value, display, index) {
	let moduleId = constant.AREA.STEP.DETAIL_LIST;
	let oldvalue = '';

	this.props.cardTable.setValByKeysAndIndex(moduleId, index, {
		[key]: {
			display: display,
			value: value
		}
	});

	click2Event.call(this, props, moduleId, key, value, oldvalue, index);
}



function getExcelExportData(props){

	//获取所有显示的列
	let columns = [];
	let colunmNames = [];

	let items = props.meta.getMeta()[constant.AREA.STEP.DETAIL_LIST].items;//所有列
	for(let i = 0; i < items.length; i ++){
		if(items[i].visible == true){
			if('opr' == items[i].attrcode) {
				continue;
			}
			columns.push(items[i].attrcode);
			colunmNames.push(items[i].label);
		}else if('pk_org' == items[i].attrcode){
			columns.push(items[i].attrcode);
			colunmNames.push(items[i].label);
		}else if('card_code' == items[i].attrcode){
			columns.push(items[i].attrcode);
			colunmNames.push(items[i].label);
		}
	}

	//获取所有显示的值
	let datashow = [];

	let result = props.cardTable.getVisibleRows(constant.AREA.STEP.DETAIL_LIST);
	if (result == null) {
		return;
	}

	for (let index = 0; index < result.length; index++) {
		
		let rowshow = [];

		for(let i = 0; i < columns.length; i ++){
			//卡片列
			let showvalue;
			if('pk_org' == columns[i]){
				showvalue = result[index].values[columns[i]].value;
			}else if('card_code' == columns[i]){
				showvalue = result[index].values[columns[i]].display
				if(undefined == showvalue || null == showvalue || '' == showvalue){
					showvalue = result[index].values[columns[i]].value;
				}
			}else{
				showvalue = result[index].values[columns[i]].display
				if(undefined == showvalue || null == showvalue || '' == showvalue){
					showvalue = result[index].values[columns[i]].value;
				}
			}

			if(undefined == showvalue || null == showvalue || '' == showvalue){
				showvalue = result[index].values[columns[i]].value;
			}

			if(showvalue == undefined) showvalue = '';

			rowshow.push("@"+showvalue+"@");
		}
		datashow.push(rowshow);
	}

	let data = {
		columns : columns,
		colunmNames : colunmNames,
		datashow : datashow
	}
	
	return data;
}

//为盘点单赋值
export function setOrgInventoryAttribute(
	props,
	row,
	index,
	pk_usedept_after_value,
	pk_usedept_after_v_value,
	moduleId,
	pk_usedept_after_name
) {
	//给盘点后字段赋值
	props.cardTable.setValByKeysAndIndex(moduleId, index, {
		// 使用状况
		pk_usingstatus_after: {
			display: row.values.pk_usingstatus_before.display,
			value: row.values.pk_usingstatus_before.value
		},
		// 管理部门版本和管理部门都需要赋值
		pk_mandept_after_v: {
			display: row.values.pk_mandept_before_v.display,
			value: row.values.pk_mandept_before_v.value
		},
		pk_mandept_after: {
			display: row.values.pk_mandept_before.display,
			value: row.values.pk_mandept_before.value
		},
		// 使用人
		assetuser_after: {
			display: row.values.assetuser_before.display,
			value: row.values.assetuser_before.value
		},
		//使用部门
		pk_usedept_after_v: {
			display: row.values.pk_usedept_before_code.value,
			value: pk_usedept_after_v_value
		},
		pk_usedept_after: {
			display: row.values.pk_usedept_before_code.value,
			value: pk_usedept_after_value
		},
		['pk_usedept_after_v.name']: {
			value: row.values.pk_usedept_before.value
		},
		['pk_usedept_after.name']: {
			value: pk_usedept_after_name != '' ? pk_usedept_after_name : row.values.pk_usedept_before.value
		},
		//存放地点
		position_after: {
			display: row.values.position_before.display,
			value: row.values.position_before.value
		},
		//货主管理组织
		pk_ownerorg_after_v: {
			display: row.values.pk_ownerorg_before_v.display,
			value: row.values.pk_ownerorg_before_v.value
		},
		pk_ownerorg_after: {
			display: row.values.pk_ownerorg_before.display,
			value: row.values.pk_ownerorg_before.value
		},
		['pk_ownerorg_after_v.name']: {
			value: row.values['pk_ownerorg_before_v.name'] ? row.values['pk_ownerorg_before_v.name'].value : ''
		},
		//使用权
		pk_equiporg_after: {
			display: row.values.pk_equiporg_before.display,
			value: row.values.pk_equiporg_before.value
		},
		pk_equiporg_after_v: {
			display: row.values.pk_equiporg_before_v.display,
			value: row.values.pk_equiporg_before_v.value
		},
		['pk_equiporg_after_v.name']: {
			value: row.values['pk_equiporg_before_v.name'] ? row.values['pk_equiporg_before_v.name'].value : ''
		}
	});
}

/*
 *切换按钮状态 
 */
export function toggleShow(that, props) {
	if (that.state.current === 0 && that.state.inventoryStatus === 'default') {
		props.button.setButtonVisible(constant.STEP_BTNS.STEP_ONE_BTNS, false);
		props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_BTNS, true);
	} else if (that.state.current === 1 && that.state.inventoryStatus === 'default') {
		props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_BTNS, false);
		props.button.setButtonVisible(constant.STEP_BTNS.STEP_THREE_BTNS, true);
	} else if (that.state.current === 1 && that.state.inventoryStatus === 'unAllot') {
		props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
		props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_HALF_BTNS, true);
	} else if (that.state.current === 1 && that.state.inventoryStatus === 'confirmed') {
		props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
		props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_BTNS, true);
	} else if (that.state.current === 1 && that.state.inventoryStatus === 'confirmedAllot') {
		props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
		props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_HALF_BTNS, true);
	} else if (that.state.current === 2) {
		props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_BTNS, false);
		props.button.setButtonVisible(constant.STEP_BTNS.STEP_TWO_HALF_BTNS, false);
		props.button.setButtonVisible(constant.STEP_BTNS.STEP_THREE_BTNS, true);
	} else if (that.state.current === 3) {
		props.button.setButtonVisible(constant.STEP_BTNS.STEP_THREE_BTNS, false);
		props.button.setButtonVisible(constant.STEP_BTNS.STEP_SAVED, true);
	} else if (that.state.current === 6 && that.state.inventoryStatus === 'confirmed') {
		props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
		props.button.setButtonVisible(constant.STEP_BTNS.SKIP_BROWSE, true);
	} else if (that.state.current === 6 && that.state.inventoryStatus === 'edit') {
		props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
		props.button.setButtonVisible(constant.STEP_BTNS.SKIP_EDIT, true);
	} else if (that.state.current === 6 && that.state.inventoryStatus === 'browse') {
		props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
		props.button.setButtonVisible(constant.STEP_BTNS.SKIP_UNEDIT, true);
	} else if (that.state.current === 7 && that.state.inventoryStatus === 'confirmedAllot') {
		props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
		props.button.setButtonVisible(constant.STEP_BTNS.RESULT_UNALLOT_BUTTON, true);
	} else if (that.state.inventoryStatus === 'confirmed' && that.state.bill_status == '0') {
		props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
		props.button.setButtonVisible(constant.STEP_BTNS.RESULT_FREE, true);
	} else if (that.state.inventoryStatus === 'confirmed' && that.state.bill_status === '1') {
		props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
		props.button.setButtonVisible(constant.STEP_BTNS.RESULT_COMMIT, true);
	} else if (that.state.inventoryStatus === 'confirmed' && that.state.bill_status === '2') {
		props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
		props.button.setButtonVisible(constant.STEP_BTNS.RESULT_APPROVING, true);
	} else if (that.state.inventoryStatus === 'confirmed' && that.state.bill_status === '3') {
		props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
		props.button.setButtonVisible(constant.STEP_BTNS.RESULT_APPROVED, true);
	} else if (that.state.inventoryStatus === 'confirmed' && that.state.bill_status === '4') {
		props.button.setButtonVisible(constant.STEP_BTNS.ALL_BUTTONS, false);
		props.button.setButtonVisible(constant.STEP_BTNS.RESULT_UNAPPROVED, true);
	}

	// 根据 saga 状态控制按钮状态 @ZHANGYPMTODO DEL
	//toggleSagaBtnVisible.call(that, props);
}

//控制 saga 按钮的状态
function toggleSagaBtnVisible(props) {
	let isError = false;
	if (this.childformData.head) {
		let saga_status = this.childformData.head.saga_status;
		isError = SagaStatus.errorValue === saga_status;
	}
	props.button.toggleErrorStatus(area.card.body_head, {
		isError: isError
	});
}

//处理盘点范围多语，不是多语字段，也不知道为啥要处理
export function handleCheck_range(check_range, flag = false) {
	//先判断是字符串还是对象 ----可能改变引用，可能只改变值
	if (typeof check_range == 'object') {
		if (check_range.value == null || check_range.value == '') {
			return;
		}
		check_range.value = cutOrShowCheckRange(check_range.value, flag);
	} else {
		if (typeof check_range == 'string') {
			check_range = cutOrShowCheckRange(check_range, flag);
		}
	}
	return check_range;
}

//截断或者显示处理
function cutOrShowCheckRange(check_range_value, flag) {
	// 获取当前语种
	let language = getLangCode() || 'simpchn';
	// 看盘点范围是否以'（' 开头
	let i = check_range_value.indexOf('(');
	// 截断显示
	if (flag) {
		if (i != 0) {
			if (check_range_value.indexOf(language) != -1) {
				check_range_value = check_range_value.substring(i, check_range_value.length);
			} else {
				check_range_value = null;
			}
		}
	} else {
		// 保存处理
		if (i == 0) {
			check_range_value = language + check_range_value;
		}
	}
	return check_range_value;
}

/*Hm9gUKDDwtNjV7Mk8onAzgXlk2sN3YqGeiNBfMPmEAaQ5tb/cjXQzjs3lVWuDzNj*/